<template>
  <view class="container">
    <!-- 连接到的设备显示 -->
    <view class="equipment_name">设备名称：{{ name }}</view>
    <view class="equipment_id">设备ID：{{ connectedDeviceId }}</view>
    <view
      :style="
        connected
          ? 'font-size:medium;word-break:break-all;color:green'
          : 'font-size:medium;word-break:break-all;color:red'
      "
    >
      状态：{{ connected ? '已连接' : '已断开' }}</view
    >
    <!-- 接收到的硬件数据 -->
    <view class="content">接收内容：</view>
    <textarea
      class="res"
      maxlength="-1"
      disabled
      :value="receiveText"
    ></textarea>
    <text> \n </text>
    <!-- 选择发送的图片 -->
    <text class="content">发送图片：</text>
    <view class="right">
      <view
        class="feedback-image-item"
        v-for="(item, index) in pics"
        :key="index"
      >
        <view
          class="close-icon"
          @tap="delImg(index)"
        >
          <uni-icons
            type="closeempty"
            size="18"
            color="#fff"
          ></uni-icons>
        </view>
        <view class="image-box">
          <image
            :src="item.url"
            mode="aspectFill"
            @tap="previewImg(item.url)"
          ></image>
        </view>
      </view>

      <view
        v-if="pics.length < 1"
        class="feedback-image-item"
        @tap="addImage"
      >
        <view class="image-box">
          <uni-icons
            type="plusempty"
            size="50"
            color="#c7c7c7"
          ></uni-icons>
        </view>
      </view>
    </view>

    <!-- 发送图片给硬件的逻辑 -->
    <button
      type="primary"
      class="button"
      @tap="Send"
    >
      发送
    </button>
  </view>
</template>

<script>
  const app = getApp()
  export default {
    data() {
      return {
        // 接收文本
        receiveText: '',
        // 上传图片
        imgUploadData: '',
        // 设备名称和id
        name: '',
        connectedDeviceId: '',
        services: {},
        characteristics: {},
        connected: true,
        searching: false,
        serviceId: '',
        characteristicId: '',
        pics: [],
      }
    },
    components: {},
    props: {},
    // 点击蓝牙条过来的时候直接监听服务和订阅特征值，并且监听返回的的硬件值
    onLoad: function (options) {
      console.log(options)
      var that = this
      that.name = options.name
      that.connectedDeviceId = options.connectedDeviceId
      //获取蓝牙设备的所有服务
      uni.getBLEDeviceServices({
        deviceId: that.connectedDeviceId,
        success: function (res) {
          console.log('打印蓝牙的服务列表', res.services)
          that.services = res.services
          that.serviceId = res.services[0].uuid
          //获取蓝牙设备指定服务中所有特征值-并且获取特征值的uuid
          uni.getBLEDeviceCharacteristics({
            deviceId: options.connectedDeviceId,
            serviceId: that.serviceId,
            success: function (res) {
              // 返回的是一个uuid的数组
              console.log('打印监听特征值的返回', res)
              ;(that.characteristics = res.characteristics),
                (that.characteristicId = res.characteristics[1].uuid)
              //启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值
              uni.notifyBLECharacteristicValueChange({
                state: true,
                deviceId: options.connectedDeviceId,
                serviceId: that.serviceId,
                characteristicId: that.characteristicId,
                success: function (res) {
                  console.log(
                    '启用notify成功并且获取特征值' + that.characteristicId
                  )
                  console.log(JSON.stringify(res))
                  // 监听传输图片返回的数据
                  that.onBLECharacteristicValueChange()
                },
                fail: function () {
                  console.log('开启notify失败' + that.characteristicId)
                },
              })
            },
          })
        },
      })
      //监听低功耗蓝牙设备链接状态变化
      uni.onBLEConnectionStateChange(function (res) {
        console.log('打印连接成功的状态', res.connected)
        that.connected = res.connected
      })
    },
    onReady: function () {},
    onShow: function () {},
    onHide: function () {},
    methods: {
      // bindInput: function(e) {
      // 	this.inputText= e.detail.value
      // 	console.log(e.detail.value);
      // },
      //分包发送数据
      Send: function () {
        var that = this
        if (that.connected) {
          // 分包发送数据
          var chunkSize = 20 // 假设每个包的大小是20字节
          var chunks = that.splitArrayIntoChunks(that.imgUploadData, chunkSize)
          //向低功耗蓝牙设备指定特征值写入二进制数据
          chunks.forEach((chunk, index) => {
            uni.writeBLECharacteristicValue({
              deviceId: that.connectedDeviceId,
              serviceId: that.serviceId,
              characteristicId: that.characteristicId,
              value: chunk.buffer,
              success: function (res) {
                if (index == chunks.length - 1) {
                  // 所有分包发送成功后的回调
                  console.log('发送指令成功:' + res.errMsg)
                  // 将接收到的数据回显
                  // this.onBLECharacteristicValueChange()
                  uni.showToast({
                    title: '数据发送成功',
                    icon: 'success',
                  })
                }
              },
              fail: function (res) {
                console.log('message发送失败:' + res.errMsg)
                uni.showToast({
                  title: '数据发送失败，请稍后重试',
                  icon: 'none',
                })
              },
            })
          })
        } else {
          uni.showModal({
            title: '提示',
            content: '蓝牙已断开',
            showCancel: false,
            success: function (res) {
              that.searching = false
            },
          })
        }
      },
      //监听低功耗蓝牙设备的特征值变化事件
      onBLECharacteristicValueChange: function () {
        console.log('onBLECharacteristicValueChange')
        var that = this
        console.log(uni.onBLECharacteristicValueChange)
        //监听低功耗蓝牙设备的特征值变化事件
        uni.onBLECharacteristicValueChange(function (res) {
          console.log('1')
          console.log('监听低功耗蓝牙设备的特征值变化事件成功', res.value)
          console.log(app.globalData.buf2string(res.value))
          //判断是否有上传图片
          if (that.imgUploadData != '') {
            var data = app.globalData.Str2Bytes(res.value)
            console.log(app.globalData.Str2Bytes(res.value))
            var receiveText = app.globalData.buf2string(data)
          } else {
            var receiveText = app.globalData.buf2string(res.value)
          }
          that.receiveText = receiveText
        })
      },
      // 分割数组为指定大小的多个分包
      splitArrayIntoChunks(array, chunkSize) {
        var chunks = []
        for (var i = 0; i < array.length; i += chunkSize) {
          chunks.push(array.slice(i, i + chunkSize))
        }
        return chunks
      },
      //删除图片
      delImg(index) {
        this.pics.splice(index, 1)
      },
      //浏览图片
      previewImg(url) {
        uni.previewImage({
          urls: [url],
        })
      },
      //添加图片
      addImage() {
        // const count = 5 - this.pics.length
        const count = 1
        uni.chooseImage({
          count: count, // 最多可以选择的图片张数，默认9
          sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
          sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
          success: (res) => {
            const tempFilePaths = res.tempFilePaths
            //获取全局唯一的文件管理器
            const fileManager = uni.getFileSystemManager()
            //读取本地文件内容。单个文件大小上限为100M
            fileManager.readFile({
              filePath: tempFilePaths[0],
              success: (readFileRes) => {
                const base64Image = readFileRes.data
                //类方法ArrayBuffer.isView()判断某对象是否为视图
                //将图片转成2进制流
                const int8a = new Uint8Array(base64Image)
                this.imgUploadData = int8a
              },
              fail: (error) => {
                console.error('读取文件失败：', error)
              },
            })
            //将图片显示界面
            tempFilePaths.forEach((item, index) => {
              if (index < count) {
                //处理小程序多选状况
                this.pics.push({
                  url: item,
                })
              }
            })
          },
        })
      },
    },
  }
</script>

<style lang="scss">
  page {
    background-color: #f8f8f8;
  }

  .container {
    padding: 30rpx;
    align-items: left;
  }

  .equipment_name {
    font-size: medium;
    word-break: break-all;
  }

  .equipment_id {
    font-size: medium;
    color: gray;
    word-break: break-all;
  }

  .content {
    font-size: medium;
    margin-top: 10px;
  }

  .input {
    margin-top: 3px;
    width: 100%;
    border: 1px solid lightgray;
    border-radius: 6px;
  }

  .res {
    margin-top: 3px;
    width: 100%;
    border: 3px solid lightgray;
    border-radius: 6px;
  }

  .button {
    position: fixed;
    width: 690rpx;
    bottom: 30rpx;
  }

  .right {
    width: 610rpx;
    display: flex;
    flex-wrap: wrap;
    padding-top: 20rpx;

    .feedback-image-item {
      position: relative;
      width: 33.33%;
      height: 0;
      padding-top: 33.33%;
      box-sizing: border-box;

      .close-icon {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: 0;
        right: 0;
        width: 44rpx;
        height: 44rpx;
        border-radius: 50%;
        background-color: #ff5a5f;
        z-index: 2;
      }

      .image-box {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: 10rpx;
        right: 10rpx;
        left: 10rpx;
        bottom: 10rpx;
        border: 1px #c7c7c7 solid;
        border-radius: 10rpx;
        overflow: hidden;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
</style>
